//
//  KDatabaseManage.m
//  Keping
//
//  Created by 柯平 on 2017/6/19.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KDatabaseManage.h"
#import <FMDB.h>
#import "NSFileManager+KP.h"

@implementation KDatabaseManage

@synthesize writablePath = _writablePath;
@synthesize databaseQueue = _databaseQueue;

static KDatabaseManage* manage = nil;

-(instancetype)init
{
    if (self == [super init]) {
        _isDatabaseOpened = NO;
        [self setWritablePath:[NSFileManager customPathWithDirectory:NSCachesDirectory isProcessInfo:YES customPath:@"keping" fileName:@"database" fileType:@"sqlite"]];
        KLog(@"writablePath:%@",_writablePath);
        [self openDatabase];
    }
    return self;
}

-(BOOL)isDatabaseOpen
{
    return _isDatabaseOpened;
}

-(void)openDatabase
{
    _databaseQueue = [FMDatabaseQueue databaseQueueWithPath:self.writablePath];
    if (_databaseQueue == 0x00) {
        _isDatabaseOpened = NO;
        return;
    }
    
    _isDatabaseOpened = YES;
    KLog(@"Open Database Success!");
    [_databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
        [db setShouldCacheStatements:YES];
    }];
}

-(void)closeDatabase
{
    if (!_isDatabaseOpened) {
        KLog(@"请求关闭数据库失败。原因：数据库未打开，或数据库打开失败。");
        return;
    }
    
    [_databaseQueue close];
    _isDatabaseOpened = NO;
    KLog(@"请求关闭数据库成功");
}

+(KDatabaseManage *)sharedManage
{
    @synchronized (self) {
        if (!manage) {
            manage = [[KDatabaseManage alloc] init];
        }
    }
    return manage;
}

+(void)releaseManage
{
    if (manage) {
        manage = nil;
    }
}

-(void)dealloc
{
    [self closeDatabase];
}

@end
